package com.hivekion.common.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hivekion.common.entity.vo.LoginUser;
import com.hivekion.common.exception.BusinessException;
import com.hivekion.system.domain.SysUser;
import com.hivekion.system.mapper.SysUserMapper;
import com.hivekion.system.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component("customUserDetailServiceImpl")
public class CustomUserDetailServiceImpl implements UserDetailsService {

      @Autowired
      SysUserMapper userMapper;

      @Autowired
      ISysMenuService menuService;

      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	    QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
	    wrapper.eq("user_name", username).last("limit 1");
	    SysUser sysUser = userMapper.selectOne(wrapper);
	    if (sysUser == null) {
		  throw new BusinessException(500, "用户不存在");
	    }
	    LoginUser user = new LoginUser();
	    BeanUtils.copyProperties(sysUser, user);
	    user.setEnabled(sysUser.getStatus().equals(0));
	    user.setUserId(sysUser.getId());
	    if (user.getUsername().equals("admin")) {
		  List<String> permissions =
			  menuService.getMenuList().stream()
				  .map(item -> item.getPerms())
				  .distinct()
				  .collect(Collectors.toList());
		  user.setPermissions(permissions);
	    } else {
		  List<String> permissions = userMapper.selectUserPermission(user.getUserId());
		  if (permissions.size() == 0) {
			permissions.add("pro:home");
		  }
		  user.setPermissions(permissions);
	    }
	    System.out.println("加密密码：" + new BCryptPasswordEncoder().encode("admin"));
	    user.setPassWord(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
	    if (!user.isEnabled()) {
		  throw new BusinessException(500, "该账户已被禁用!");
	    } else if (!user.isAccountNonLocked()) {
		  throw new LockedException("该账号已被锁定!");
	    } else if (!user.isAccountNonExpired()) {
		  throw new AccountExpiredException("该账号已过期!");
	    } else if (!user.isCredentialsNonExpired()) {
		  throw new CredentialsExpiredException("该账户的登录凭证已过期，请重新登录!");
	    }
	    System.out.println("当前用户信息：" + user.getUsername());
	    return user;
      }
}
